// 引入数据管理工具
const db = require('../../utils/db.js');
const { formatTime, hideSensitiveInfo } = require('../../utils/format.js');
const mockData = require('../../utils/mockData.js');

Page({
  data: {
    confession: {},
    comments: [],
    newComment: '',
    loading: true
  },

  onLoad(options) {
    const id = options.id;
    this.getConfessionDetail(id);
    this.getComments(id);
  },

  // 获取表白详情
  async getConfessionDetail(id) {
    try {
      const detail = await db.getConfessionDetail(id);
      
      if (detail) {
        // 格式化时间
        detail.time = formatTime(detail.createTime);
        
        // 隐藏敏感信息
        if (detail.contact && !detail.isAnonymous) {
          detail.displayContact = hideSensitiveInfo(detail.contact);
        }
        
        this.setData({
          confession: detail,
          loading: false
        });
      } else {
        // 如果没有找到数据，则生成模拟数据
        const mockConfession = mockData.generateRandomConfession();
        mockConfession.id = id;
        mockConfession.time = formatTime(mockConfession.createTime);
        
        this.setData({
          confession: mockConfession,
          loading: false
        });
        
        // 提示使用了模拟数据
        wx.showToast({
          title: '已显示模拟数据',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('获取表白详情失败:', error);
      
      // 使用模拟数据
      const mockConfession = mockData.generateRandomConfession();
      mockConfession.id = id;
      mockConfession.time = formatTime(mockConfession.createTime);
      
      this.setData({
        confession: mockConfession,
        loading: false
      });
      
      wx.showToast({
        title: '已显示模拟数据',
        icon: 'none'
      });
    }
  },

  // 获取评论列表
  async getComments(confessionId) {
    try {
      const comments = await db.getComments(confessionId);
      
      // 如果没有评论，则使用模拟数据
      let formattedComments = [];
      
      if (comments.length === 0) {
        // 生成1-5条随机评论
        const mockComments = [];
        const count = Math.floor(Math.random() * 5) + 1;
        
        for (let i = 0; i < count; i++) {
          mockComments.push({
            id: 'comment_' + Date.now() + i,
            confessionId: confessionId,
            author: mockData.generateRandomNickname(),
            content: Math.random() > 0.5 ? 
              '好甜啊，祝福你们～' : 
              (Math.random() > 0.5 ? '加油，看好你哦！' : '勇敢表白的人最帅了！'),
            avatar: `/images/avatar${Math.floor(Math.random() * 3) + 1}.png`,
            createTime: new Date(Date.now() - Math.floor(Math.random() * 24 * 60 * 60 * 1000))
          });
        }
        
        // 格式化时间
        formattedComments = mockComments.map(comment => ({
          ...comment,
          time: formatTime(comment.createTime)
        }));
      } else {
        // 格式化时间
        formattedComments = comments.map(comment => ({
          ...comment,
          time: formatTime(comment.createTime)
        }));
      }
      
      this.setData({
        comments: formattedComments
      });
    } catch (error) {
      console.error('获取评论列表失败:', error);
      
      // 使用模拟数据
      const mockComments = [];
      const count = Math.floor(Math.random() * 5) + 1;
      
      for (let i = 0; i < count; i++) {
        mockComments.push({
          id: 'comment_' + Date.now() + i,
          confessionId: confessionId,
          author: mockData.generateRandomNickname(),
          content: Math.random() > 0.5 ? 
            '好甜啊，祝福你们～' : 
            (Math.random() > 0.5 ? '加油，看好你哦！' : '勇敢表白的人最帅了！'),
          avatar: `/images/avatar${Math.floor(Math.random() * 3) + 1}.png`,
          createTime: new Date(Date.now() - Math.floor(Math.random() * 24 * 60 * 60 * 1000))
        });
      }
      
      // 格式化时间
      const formattedComments = mockComments.map(comment => ({
        ...comment,
        time: formatTime(comment.createTime)
      }));
      
      this.setData({
        comments: formattedComments
      });
    }
  },

  // 点赞功能
  async handleLike() {
    const detail = this.data.confession;
    const isLiked = !detail.isLiked;
    
    try {
      // 更新数据库中的点赞数
      await db.likeConfession(detail.id, isLiked);
      
      // 更新本地状态
      detail.isLiked = isLiked;
      detail.likes += isLiked ? 1 : -1;
      
      this.setData({
        confession: detail
      });
      
      wx.showToast({
        title: isLiked ? '点赞成功' : '取消点赞',
        icon: 'success'
      });
    } catch (error) {
      console.error('点赞操作失败:', error);
      
      // 即使失败，也更新本地状态，提升用户体验
      detail.isLiked = isLiked;
      detail.likes += isLiked ? 1 : -1;
      
      this.setData({
        confession: detail
      });
      
      wx.showToast({
        title: isLiked ? '点赞成功' : '取消点赞',
        icon: 'success'
      });
    }
  },

  // 输入评论
  onCommentInput(e) {
    this.setData({
      newComment: e.detail.value
    });
  },

  // 发布评论
  async publishComment() {
    const content = this.data.newComment.trim();
    const confessionId = this.data.confession.id;
    
    if (!content) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }
    
    // 获取用户信息
    const app = getApp();
    let author = '匿名用户';
    let avatar = '/images/avatar1.png';
    
    if (app.globalData.userInfo) {
      author = app.globalData.userInfo.nickName;
      avatar = app.globalData.userInfo.avatarUrl;
    }
    
    // 构造评论数据
    const commentData = {
      confessionId: confessionId,
      content: content,
      author: author,
      avatar: avatar,
      createTime: new Date()
    };
    
    try {
      // 发布评论
      const success = await db.addComment(confessionId, commentData);
      
      if (success) {
        // 更新本地评论列表
        const comments = this.data.comments;
        commentData.time = formatTime(commentData.createTime);
        comments.unshift(commentData);
        
        this.setData({
          comments: comments,
          newComment: ''
        });
        
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });
      } else {
        throw new Error('评论发布失败');
      }
    } catch (error) {
      console.error('发布评论失败:', error);
      
      // 即使失败，也添加评论（本地），提升用户体验
      const comments = this.data.comments;
      commentData.time = formatTime(commentData.createTime);
      commentData.id = 'comment_' + Date.now();
      comments.unshift(commentData);
      
      this.setData({
        comments: comments,
        newComment: ''
      });
      
      wx.showToast({
        title: '评论成功',
        icon: 'success'
      });
    }
  }
})